<!--
 * @Author: yuanweijiang
 * @Date: 2025-03-31 18:09:08
 * @LastEditors: yuanweijiang
-->
<template>
	<div class="layout-padding">
		<splitpanes>
			<pane size="15">
				<div class="layout-padding-auto layout-padding-view">
					<div class="flex justify-between items-center px-2 py-2">
						<span class="font-bold" style="font-size: 16px">服务目录</span>
						<el-button icon="Plus" type="primary" @click="handleAddGroup">分组</el-button>
					</div>
					<el-scrollbar>
						<el-input class="mb-3" v-model="filterText" :suffix-icon="Search" size="large" placeholder="输入服务目录名称查询" />
						<el-tree ref="treeRef" :data="dataList" node-key="id" :filter-node-method="filterNode" :props="defaultProps" accordion>
							<template #default="{ node, data }">
								<div class="w-full flex justify-between items-center">
									<span @click="handleFilter(data)">{{ node.label }}</span>
									<div class="flex gap-2" v-if="node.label !== '全部'">
										<el-icon class="cursor-pointer" @click.stop="handleEditGroup(data)"><Edit /></el-icon>
										<el-icon v-if="!data.parentId" class="cursor-pointer" @click.stop="handleAddGroup(data)"><Plus /></el-icon>
										<el-icon class="cursor-pointer" @click.stop="handleDelGroup(data)"><Delete /></el-icon>
									</div>
								</div>
							</template>
						</el-tree>
					</el-scrollbar>
				</div>
			</pane>
			<pane class="ml8">
				<div class="layout-padding-auto layout-padding-view">
					<div class="layout-padding-auto layout-padding-view">
						<div>
							<el-form :inline="true" :model="state.queryForm" @keyup.enter="getDataList" ref="queryRef">
								<el-form-item prop="serviceName" label="服务名称">
									<el-input placeholder="请输入服务名称" clearable style="max-width: 150px" v-model="state.queryForm.serviceName" />
								</el-form-item>
								<el-form-item prop="describeStr" label="描述">
									<el-input placeholder="请输入描述" clearable style="max-width: 150px" v-model="state.queryForm.describeStr" />
								</el-form-item>
								<el-form-item prop="serviceType" label="服务类型">
									<el-select v-model="state.queryForm.serviceType" placeholder="请选择" style="max-width: 150px">
										<el-option v-for="item in serviceTypeList" :key="item.label" :label="item.label" :value="item.value" />
									</el-select>
								</el-form-item>
								<el-form-item prop="serviceStatus" label="服务状态">
									<el-select v-model="state.queryForm.serviceStatus" placeholder="请选择" style="max-width: 150px">
										<el-option v-for="item in serviceList" :key="item.label" :label="item.label" :value="item.value" />
									</el-select>
								</el-form-item>
								<el-form-item prop="updateTime" label="更新时间">
									<el-date-picker
										v-model="timeArr"
										type="daterange"
										style="max-width: 230px"
										value-format="YYYY-MM-DD HH:mm:ss"
										@change="changeTime"
										range-separator="-"
										start-placeholder="开始时间"
										end-placeholder="结束时间"
									>
									</el-date-picker>
								</el-form-item>
							</el-form>
							<div class="flex justify-between">
								<el-form-item>
									<el-button @click="addHandle" class="" icon="Plus" type="primary"> 创建服务 </el-button>
									<el-button @click="selectionDown" :disabled="ids.length === 0" class="ml10" icon="Plus" type="primary"> 批量上线 </el-button>
								</el-form-item>
								<el-form-item>
									<el-button @click="query" class="ml10" icon="search" type="primary"> 查询 </el-button>
									<el-button icon="Refresh" @click="resetQuery">重置</el-button>
								</el-form-item>
							</div>
						</div>
						<el-table
							ref="tableRef"
							:data="state.dataList"
							:tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
							row-key="path"
							style="width: 100%"
							:cell-style="tableStyle.cellStyle"
							:header-cell-style="tableStyle?.headerCellStyle"
							@selection-change="handleSelectionChange"
						>
							<el-table-column type="selection" width="55" />
							<el-table-column prop="serviceName" label="服务名称" />
							<el-table-column prop="serviceType" label="类型">
								<template #default="scope">
									{{ scope.row.serviceType === 1 ? '数据表' : '数据服务' }}
								</template>
							</el-table-column>
							<el-table-column prop="defaultStr" label="标签" width="230">
								<template #default="scope">
									<div class="flex gap-2 items-center justify-center">
										<el-tag size="large" v-for="item in scope.row.label?.split(',')" :key="item">{{ item }}</el-tag>
										<el-icon class="ml-2 border cursor-pointer" @click="handAddTag(scope)"><Plus /></el-icon>
									</div>
								</template>
							</el-table-column>
							<el-table-column prop="serviceUrl" label="服务地址" />
							<el-table-column prop="apiUrl" label="API地址" show-overflow-tooltip>
								<template #default="scope"
									><div class="api-url">
										<span> {{ filterApi(scope.row.apiUrl) }}</span>
										<img v-if="scope.row.apiUrl" src="../复制-未选中@2x.png" alt="" @click="copy(scope.row.apiUrl)" />
									</div>
								</template>
							</el-table-column>
							<el-table-column prop="describeStr" label="描述" />
							<el-table-column prop="updateTime" label="更新时间" show-overflow-tooltip />
							<el-table-column prop="onEnable" label="是否鉴权">
								<template #default="scope">
									<el-switch
										v-model="scope.row.isAuthentication"
										class="ml-2"
										:active-value="1"
										:inactive-value="2"
										@change="switchChange(scope.row)"
										style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
									/>
								</template>
							</el-table-column>
							<el-table-column prop="serviceStatus" label="服务状态">
								<template #default="scope">
									{{ scope.row.serviceStatus === 1 ? '在线' : '下线' }}
								</template>
							</el-table-column>
							<el-table-column prop="date" label="操作" width="230">
								<template #default="scope">
									<el-button class="ml10 is-text" icon="bottom" type="primary" @click="handleServiceStatus(scope.row.serviceId)">
										{{ scope.row.serviceStatus === 1 ? '下线' : '上线' }}
									</el-button>
									<el-button class="ml10 is-text" icon="edit" type="primary" @click="handleEdit(scope.row.serviceId)"> 编辑 </el-button>
									<el-button class="ml10 is-text" icon="delete" type="primary" @click="handleDel(scope.row.serviceId)"> 删除 </el-button>
								</template>
							</el-table-column>
						</el-table>
						<Pagination v-bind="state.pagination" @current-change="currentChangeHandle" @size-change="sizeChangeHandle"> </Pagination>
					</div>
				</div>
			</pane>
		</splitpanes>

		<addGroup ref="addGroupRef" @refresh="gruopInit" />

		<addTag ref="addTagRef" @refresh="uplateTag" />

		<!-- 创建服务 -->
		<createService ref="createServiceRef" @addLayer="getDataList" />
	</div>
</template>
<script setup lang="ts">
import { Search } from '@element-plus/icons-vue';
import addTag from './components/addTag.vue';
import addGroup from './components/addgrouping.vue';
import { BasicTableProps, useTable } from '/@/hooks/table';
import { useI18n } from 'vue-i18n';
import {
	getServiceCatalogTree,
	getServiceCatalogInfo,
	updateServiceManagementData,
	delServiceCatalog,
	getServiceManagementList,
	modifyAuthStatus,
	updateServiceStatus,
	delServiceManagementData,
	getServiceManagementData,
} from '/@/api/datasource';
import { useMessage, useMessageBox } from '/@/hooks/message';
import createService from './components/createService.vue';
const inputValue = ref('');
const addGroupRef = ref('');
const { t } = useI18n();

const addTagRef = ref('');
const createServiceRef = ref('');
const defaultProps = ref({
	children: 'children',
	label: 'name',
});
const dataList = ref([]);
const timeArr = ref([]);
const state: BasicTableProps = reactive<BasicTableProps>({
	queryForm: {
		serviceCatalogId: '',
	},
	pageList: getServiceManagementList,
	props: {
		item: 'records',
		totalCount: 'total',
	},
});
const treeRef = ref();
const { getDataList, tableStyle, currentChangeHandle, sizeChangeHandle } = useTable(state);

const serviceList = ref([
	{
		label: '上线',
		value: 1,
	},
	{
		label: '未上线',
		value: 2,
	},
]);

const serviceTypeList = ref([
	{
		label: '数据服务',
		value: 2,
	},
	{
		label: '数据表',
		value: 1,
	},
]);
const resetQuery = () => {
	state.queryForm = {};
	timeArr.value = [];
	getDataList();
};
const ids = ref([]);
async function switchChange(item) {
	try {
		await modifyAuthStatus(item);
		useMessage().success('修改成功');
		getDataList();
	} catch (error) {}
}
function changeTime(time) {
	state.queryForm.startTime = time[0];
	state.queryForm.endTime = time[1];
}
function filterApi(url) {
	return window.location.origin + '/zsxw-city-api-dev' + url;
}
async function handleDel(id) {
	try {
		await useMessageBox().confirm(t('common.delConfirmText'));
	} catch {
		return;
	}
	try {
		await delServiceManagementData([id]);
		useMessage().success('删除成功');
		getDataList();
	} catch (error) {}
}
const handleSelectionChange = (arr: any) => {
	ids.value = arr.map((item) => {
		return item.serviceId;
	});
};
function handleServiceStatus(id) {
	updateServiceStatus([id]).then((res) => {
		useMessage().success(res.data);
		getDataList();
	});
}
function handleEdit(id) {
	getServiceManagementData({ serviceId: id }).then((res) => {
		let { data } = res;
		data.serviceType == 2 ? (createServiceRef.value.activeIndex = 1) : (createServiceRef.value.activeIndex = 0);
		createServiceRef.value.dialogWidth = 1500;
		createServiceRef.value.openDialog({ queryForm: data });
	});
}
const copy = async (url) => {
	const textarea = document.createElement('textarea');
	textarea.value = filterApi(url);
	document.body.appendChild(textarea);
	textarea.select();

	try {
		// 尝试执行复制操作
		const success = document.execCommand('copy');
		if (success) {
			useMessage().success('复制成功');
		} else {
			useMessage().error('复制失败');
		}
	} catch (error) {
		useMessage().error('复制失败');
	}
	document.body.removeChild(textarea);
};
function selectionDown() {
	updateServiceStatus(ids.value).then((res) => {
		useMessage().success(res.data);
		getDataList();
	});
}
function handleFilter(data) {
	if (data.id === '全部') {
		state.queryForm.serviceCatalogId = '';
		getDataList();
		return;
	}
	if (!data.parentId) return;
	state.queryForm.serviceCatalogId = Number(data.id);
	getDataList();
}
const query = () => {
	state.dataList = [];
	getDataList();
};
const filterText = ref('');
function handleAddGroup(data) {
	addGroupRef.value.openDialog({ queryForm: { parentId: data.id, parentName: data.name } });
}
async function handleDelGroup(data) {
	try {
		await useMessageBox().confirm(t('common.delConfirmText'));
	} catch {
		return;
	}
	try {
		await delServiceCatalog({ serviceCatalogId: data.id });
		useMessage().success('删除成功');
		gruopInit();
	} catch (error) {}
}
async function handleEditGroup(res) {
	const { data } = await getServiceCatalogInfo({ serviceCatalogId: res.id });
	addGroupRef.value.openDialog({ queryForm: data, title: '编辑分组' });
}
watch(filterText, (val) => {
	treeRef.value!.filter(val);
});

const filterNode = (value, data) => {
	if (!value) return true;
	return data.name.includes(value);
};
function handAddTag(scope) {
	if (scope.row.label) {
		addTagRef.value.openDialog({ tagList: scope.row.label.split(','), id: scope.row.serviceId });
	} else {
		addTagRef.value.openDialog({ id: scope.row.serviceId });
	}
}
function addHandle() {
	createServiceRef.value.openDialog({});
}
async function uplateTag(tagArr) {
	// let newObj = state.dataList.filter((item) => {
	// 	return item.serviceId == tagArr.serviceId;
	// });
	// newObj[0].label = tagArr.tagList.join(',');
	try {
		await updateServiceManagementData({ serviceId: Number(tagArr.id), label: tagArr.tagList.join(',') });
		useMessage().success('标签修改成功');
		getDataList();
	} catch (error) {}
}
function gruopInit(params: type) {
	getServiceCatalogTree().then((res) => {
		let { data } = res;
		dataList.value = data;
		dataList.value.unshift({ id: '全部', name: '全部', children: [] });
	});
}
gruopInit();
</script>
<style lang="scss" scoped>
.el-tree {
	font-size: 16px;
}
.api-url {
	display: flex;
	span {
		color: #527dda;
		width: 160px;
		display: inline-block;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	img {
		width: 16px;
		height: 16px;
	}
}
</style>
